package com.mynetwork.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
import java.util.StringTokenizer;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

public class Utils
{
	public static boolean isNotDeveloped = false;
	private static final String TAG = "Utils";
	public static final String KEY_IS_FIRST = "isFirst";
	
	public static String getTodayDateFormat() {
		return getTodayDateFormat("yyyyMMddHHmmssSS");
	}
	
	public static String getTodayDateFormat(String format) {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat sdfNow = new SimpleDateFormat(format);
		return sdfNow.format(date);
	}
	
	public static String getcurrentParseDate(){
		long time = System.currentTimeMillis();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dd = new Date(time);
		return sdf.format(dd);
	}
	
	public static String getStringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours   = totalSeconds / 3600;
        StringBuilder Builder = new StringBuilder();
        Formatter mFormatter = new Formatter(Builder, Locale.getDefault());
        
        if (hours > 10) {
        	return mFormatter.format("%02d:%02d", 0, 0).toString();
        } else if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }
    
	public static byte[] getBytesFromFile(File file) throws IOException {
	    InputStream is = new FileInputStream(file);

	    // Get the size of the file
	    long length = file.length();

	    if (length > Integer.MAX_VALUE) {
	      // File is too large
	    }

	    byte[] bytes = new byte[(int) length];

	    int offset = 0;
	    int numRead = 0;
	    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
	      offset += numRead;
	    }

	    if (offset < bytes.length) {
	      throw new IOException("Could not completely read file " + file.getName());
	    }

	    is.close();
	    return bytes;
	}
	
	public static String getOnlyFilename(String file) {
		String[] str = file.split("\\.");
		if (str == null || str.length == 0)
			return file;
		String result = "";
		result = str[0];
		for (int i=1;i<str.length - 1;i++) {
			result += "." + str[i];
		}
		return result;
	}
	
	public static String getLastFileName(String url) {
	    int slashIndex = url.lastIndexOf('/'); 
	    String filenameWithoutExtension; 
    	filenameWithoutExtension = url.substring(slashIndex + 1); 
	    return "/" + filenameWithoutExtension;
    }
    
	public static String getPathSlash(String path) {
		if (path.charAt(0) != '/')
			path = "/" + path;
		return path;
	}
	
	public static float divide(float a, float b) {
		float result = a/b;
		if (a < 0)
			result += (result - a);
		
		return result;
	}
	
	public static int parseInt(String value, int def) {
		int result = def;
		try {
			if (value != null && value.length() > 0) {
				if (value.lastIndexOf('.') < 0)
					result = Integer.parseInt(value);
				else 
					result = (int) Float.parseFloat(value);
			}
				
		} catch (Exception e) {
			result = def;
			Log.e(TAG, "" + e);
		}
		return result;
	}
	
	public static long parseLong(String value, long def) {
		long result = def;
		try {
			if (value != null && value.length() > 0)
				result = Long.parseLong(value);
		} catch (Exception e) {
			result = def;
			Log.e(TAG, "" + e);
		}
		return result;
	}
	
	public static float parseFloat(String value) {
		return parseFloat(value,0);
	}
	
	public static float parseFloat(String value, float def) {
		float result = def;
		try {
			if (value != null && value.length() > 0)
				result = Float.parseFloat(value);
		} catch (Exception e) {
			result = def;
			Log.e(TAG, "" + e);
		}
		return result;
	}
	
	public static double parseDouble(String value) {
		double result = 0.0f;
		try {
			if (value != null && value.length() > 0)
				result = Double.parseDouble(value);
		} catch (Exception e) {
			result = 0.0;
			Log.e(TAG, "" + e);
		}
		return result;
	}
	
	public static String separationText(String text,TextPaint paint,int maxSize) {
		float[] widths = new float[text.length()];
		paint.getTextWidths(text, widths);

		int textWidth = 0;
		StringBuilder sepText = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
        	if (text.charAt(i) == '.') {
        		sepText.append(text.charAt(i) + "\n");
        		textWidth = 0;
        	} else if (maxSize != 0 && textWidth > (maxSize - 10)) {
        		sepText.append("\n" + text.charAt(i));
        		textWidth = (int) widths[i];
        	} else {
        		sepText.append(text.charAt(i));
        		textWidth += widths[i];
        	}
        }
        return sepText.toString();
	}
	
//	public static String separationText(String text,TextPaint paint,int maxSize) {
//		float[] widths = new float[text.length()];
//		paint.getTextWidths(text, widths);
//
//		int startPos = 0;
//		int endPos = 0;
//		StringBuilder sepText = new StringBuilder();
//		
//		endPos = paint.breakText(text, true, maxSize, null);
//		sepText.append(text.substring(startPos,endPos) + "\n");
//		
//        while(endPos < text.length() - 1) {
//        	startPos = endPos;
//        	String tmpStr = text.substring(startPos,text.length());
//        	endPos = paint.breakText(tmpStr, true, maxSize, null);
//        	endPos += startPos;
//        	sepText.append(text.substring(startPos,endPos) + "\n");
//        }
//        return sepText.toString();
//	}
	
	public static int textWidth(String text,TextPaint paint) {
		StringTokenizer tokens = new StringTokenizer(text,"\n");
		int maxWidth = 0;
		for (int loop = 1;tokens.hasMoreElements();loop++) {
			int textWidth = 0;
			String element = tokens.nextToken();
			float[] widths = new float[element.length()];
			paint.getTextWidths(element, widths);
			for (int i = 0; i < element.length(); i++) {
				textWidth += widths[i];
			}
			if (maxWidth < textWidth)
				maxWidth = textWidth;
		}
		return maxWidth;
	}
}